import base64
import time
import ddddocr
import execjs
import requests
from 练习.轨迹 import detect_displacement

def get_slide_img():
    url = 'https://iv.jd.com/slide/g.html'
    params = {
        'appId': '1604ebb2287',
        'scene': 'login',
        'product': 'click-bind-suspend',
        'e': '2PM7KF3C342YFESUAYETQVE3XVZJNKXN2EAKOHQ6VFUF5LVF3363RV37RAGIDULDDMA3JN2EUH4326EQ27P3M6OJJY',
        'j':'',
        'lang': 'zh_CN',
    }
    r =  sess.get(url = url,params = params).json()
    return r

def save_img(data):
    bg = base64.b64decode(data['bg'].encode())
    fg = base64.b64decode(data['patch'].encode())
    with open('../static/bg.jpg','wb') as f:
        f.write(bg)
    with open('../static/fg.jpg','wb') as f:
        f.write(fg)

    print('滑块图片保存成功！')

def getSeild():
    ocr = ddddocr.DdddOcr(det=False,ocr=False,show_ad=False)
    with open('../static/bg.jpg','rb') as f:
        bg = f.read()
    with open('../static/fg.jpg', 'rb') as f:
        fg = f.read()
    target = ocr.slide_match(bg,fg,simple_target=True)
    return target['target'][0]
def getd(w):
    with open('./京东滑块.js','r',encoding='utf-8') as f:
        js_code = f.read()
    return execjs.compile(js_code).call('getCoordinate',w)
def get_slide():

    # 获取滑块信息
    data = get_slide_img()
    # 保存图片并获取滑块距离
    save_img(data)
    slied_windth = round(((242/360) * getSeild() + 21))
    print(slied_windth)
    # 获取滑动轨迹
    d = getd(slied_windth)

    # 休眠7秒
    time.sleep(7)
    c = data['challenge']

    url = 'https://iv.jd.com/slide/s.html'
    params = {
        "d": d,
        "c": c,
        "w": "242",
        "appId": "1604ebb2287",
        "scene": "login",
        "product": "click-bind-suspend",
        "e": "2PM7KF3C342YFESUAYETQVE3XVZJNKXN2EAKOHQ6VFUF5LVF3363RV37RAGIDULDDMA3JN2EUH4326EQ27P3M6OJJY",
        "j": "",
        "s": "235389954183362411",
        "o": "11111",
        "o1": "0",
        "u": "https://passport.jd.com/new/login.aspx?ReturnUrl=https%3A%2F%2Fwww.jd.com%2F%3Fcu%3Dtrue%26utm_source%3Dbaidu-pinzhuan%26utm_medium%3Dcpc%26utm_campaign%3Dt_288551095_baidupinzhuan%26utm_term%3D0f3d30c8dba7459bb52f2eb5eba8ac7d_0_903f455055b14c4e99422e518d9a1d36",
        "lang": "zh_CN",
        "callback": "jsonp_028078467996926904"
    }

    r = sess.get(url, params=params)
    print(r.text)

if __name__ == '__main__':
    sess = requests.session()
    sess.headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36",
    }
    # 滑块验证
    for i in range(10):
        get_slide()
